package com.taru.wxhsh.controller;

import com.taru.wxhsh.common.JsonResult;
import com.taru.wxhsh.constant.CommonConstants;
import com.taru.wxhsh.constant.JResponseConstants;
import com.taru.wxhsh.pojo.Admin;
import com.taru.wxhsh.pojo.User;
import com.taru.wxhsh.service.UserLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by HuKang on 2018/6/5.
 */
@Controller
public class UserLoginController {
    Logger logger  = LoggerFactory.getLogger(UserLoginController.class);
    @Autowired
    UserLoginService userLoginService;

    @ResponseBody
    @RequestMapping("/admin/login")
    public Object login(String username, String password, HttpServletRequest request, HttpServletResponse response){
        JsonResult<Admin> result = null;
        try {
            Admin user = userLoginService.login(username,password);
            if (user!=null){
                result = new JsonResult<>(JResponseConstants.STATUS_OK,"登陆成功",user);
                Cookie cookie =new Cookie(CommonConstants.TOKEN_KEY, CommonConstants.SIMPLE_TOKEN);
                cookie.setMaxAge(86400);
                cookie.setPath("/");
                response.addCookie(cookie);

            }else {
                result = new JsonResult<>(JResponseConstants.STATUS_NO_DATA,"用户名或密码错误");
            }
        }catch (Exception ex){
            logger.error("未知异常:{}",ex.getMessage());
            result =new JsonResult<>(JResponseConstants.STATUS_ERROR,"未知异常");
        }
        return result;
    }

}
